/*
 * DA6.c
 *
 * Created: 4/15/2014 3:11:32 PM
 *  Author: Omar Salazar
 */ 

#define F_CPU 8000000UL //XTAL = 8MHZ
#include <avr/io.h>
#include <util/delay.h>

uint16_t ReadADC(uint8_t ADCchannel)
{
	// select ADC channel with safety mask
	ADMUX = (ADMUX & 0xF0) | (ADCchannel & 0x0F);
	// single conversion mode
	ADCSRA |= (1<<ADSC);
	// wait until ADC conversion is complete
	while( ADCSRA & (1<<ADSC) );
	return ADC;
}


int main()
{
	float low, high;	//variables to hold the low and high values of ADC
	int pot;			//variable to represent the value of the potentiometer
	
	PORTC = 0x00;       //Clear PORTC
	DDRB = 0x02;		//Set PB1 as output
	DDRD = 0xFF;        //Set PORTD as output
	DDRC = 0x00;		//Set PORTC as input
	
	// Timer1 Setup:
	TCCR1A = 0xA2;		//0xA2=10100010b. Clear OC1A/OC1B on compare match
	TCCR1B = 0x1A;		//0x1A=00011010b. Prescaler of 8, Fast PWM
	
	// Setup ICR1 (for servo)
	ICR1 = 20000;
	
	ADMUX = 64;         //AVCC with external capacitor at AREF pin
	ADCSRA = 0x87;      //ADC enable. select ck/128=62500
	
	while(1)
	{
//*********This code segment controls the stepper motor**************************
		pot = ReadADC(3)/6;			//read in ADC value from PC3, divide by 6 for visible slow speed
		PORTD = 0x66;				//output to PD1,PD2,PD5,PD6
		for(int i=0;i<pot+20;i++)	//delay for the potentiometer value
		_delay_ms(1);				//library delay
		PORTD = 0x33;				//output to PD0,PD1,PD4,PD5
		for(int i=0;i<pot+20;i++)	//delay for the potentiometer value
		_delay_ms(1);				//library delay
		PORTD = 0x99;				//output to PD0,PD3,PD4,PD7
		for(int i=0;i<pot+20;i++)	//delay for the potentiometer value
		_delay_ms(1);				//library delay
		PORTD = 0xCC;				//output to PD2,PD3,PD6,PD7
		for(int i=0;i<pot+20;i++)	//delay for the potentiometer value
		_delay_ms(1);				//library delay
//********************************************************************************

//**********This code segment controls the servo motor****************************
		ADMUX = (ADMUX & 0xF0) | (0 & 0x0F);	//select ADC channel with safety mask
		ADCSRA|=(1<<ADSC);						//start conversion
		while(ADCSRA & (1<<ADSC));				//wait for conversion to finish
		//Send ADC values to respected variables:
		low = ADCL;			//Low part of ADC to low
		high = ADCH;		//High part of ADC to High
		
		//Scale:
		high = high*256.0;
		high = high+low;
		high = (1800.0/1024.0)*high;

		OCR1A = 500+high;	//send 500 + high to Output Compare Register	
	}
	return 0;
}